/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hello;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

import java.io.*;
import javax.microedition.io.*;
import java.lang.String.*;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import java.lang.Math;

import com.beartronics.FP;

// Solo per debug (caricamento dati fittizi):
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import java.io.*;
import java.util.*;
/////////////////////////////////////////

/**
 * @author luca
 */
public class mTrafficLC extends MIDlet implements CommandListener {

    public int DEBUG_FLAG = 0; // Set to 0 to prevent debug messages from being displayed.
    public String VERSION = "0.0.1"; // 

 public int[][][] Segments =   {{{40,66},{30,66}}, 
                              {{41,53},{31,53}}, 
                              {{56,27},{48,19}}, 
                              {{64,25},{59,16}}, 
                              {{74,23},{70,13}}, 
                              {{89,21},{89,11}}, 
                              {{104,22},{106,12}},
                              {{116,29},{120,20}},
                              {{126,39},{133,31}},
                              {{134,51},{141,43}},
                              {{138,60},{145,52}},
                              {{138,73},{148,73}},
                              {{137,80},{147,80}},
                              {{133,87},{143,87}},
                              {{129,97},{139,97}},
                              {{126,109},{136,109}},
                              {{122,117},{129,124}},
                              {{108,120},{112,128}},
                              {{93,121},{94,130}},
                              {{77,126},{75,135}},
                              {{63,127},{59,136}},
                              {{49,118},{44,126}},
                              {{40,102},{32,109}},
                              {{39,87},{31,94}}};

public int[][][] segment_color ={{{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}},
                {{0,0,0},{0,0,0}}};

public String name[] =  {" 1-Aure-Bocc" ,
        " 2-Bocc-Cass" ,
        " 3-Cass-CassB" ,
        " 5-CassB-Flam" ,
        " 6-Flam-Sala" ,
        " 8-Sala-A1FI" ,
        "10-A1FI-Nome" ,
        "11-Nome-Centr" ,
        "12-Centr-Tibu" ,
        "13-Tibu-A 24" ,
        "14-A 24-Rust" ,
        "15-Rust-Pren" ,
        "16-Pren-Casi" ,
        "18-Casi-A1NA" ,
        "19-A1NA-Tusc" ,
        "21-Tusc-Appi" ,
        "23-Appi-Arde" ,
        "24-Arde-Laur" ,
        "25-Laur-Pont" ,
        "26-Pont-Osti" ,
        "27-Osti-Fium" ,
        "30-Fium-Pisa" ,
        "32-Pisa-Pesc" ,
        "33-Pesc-Aure" };

public int CODES_NUMBER = 6;
// Green, Blue, Yellow, Orange, Red, Black
public int codes[][][] = { {{0, 255, 0},{0,180,0}} , {{0, 255, 255},{0,0,200}} , {{255, 255, 0},{255,255,0}} , {{255, 128, 0},{255,128,0}} , {{255, 0, 0},{255,100,100}} , {{0, 0, 0},{0,0,0}}   };   
  

public int KINT = 0;
public int KEXT = 1;

public String contents;

  private Display display;

  private MyCanvas canvas;

  public mTrafficLC() {
    display = Display.getDisplay(this);
    canvas = new MyCanvas(this);
  }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
  protected void startApp() {
        boolean res = true;
   
        if (DEBUG_FLAG == 1) {
            // Just for debugging without connecting:
 //           readFile();
        } else {             
            switchDisplayable(null, getTxtContents());
            txtContents.setString("Scaricamento in corso...\n");
            try {
                res = getViaStreamConnection("http://www.baluardoproductions.com/gra/");
            } catch (IOException e) {
                System.out.println("IOException " + e);
                e.printStackTrace();
                txtContents.setString(txtContents.getString()+"Impossibile scaricare dati: "+ e.toString());         
                res = false;
            }
        }        
        if (res == true) 
            res = getColors();
        
        if (res == true)
            display.setCurrent(canvas); 
        else
            txtContents.setString(txtContents.getString()+"C'e' stato un errore,il grafico non sarà attendibile.\n");
  }

  protected void pauseApp() {
  }

  protected void destroyApp(boolean unconditional) {
  }

  public void exitMIDlet() {
    destroyApp(true);
    notifyDestroyed();
  }

  public Display getDisplay() {
    return display;
  }    
  //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
  private Command exitCommand;
  private Command okCommand;
  private Command okCommand1;
  private Command exitCommand1;
  private Form txtRisultato;
  private ImageItem imageItem;
  private TextBox txtContents;
  private Image image1;
  //</editor-fold>//GEN-END:|fields|0|

  //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
  //</editor-fold>//GEN-END:|methods|0|

  //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
  /**
   * Initilizes the application.
   * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
   */
  private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
  }//GEN-BEGIN:|0-initialize|2|
  //</editor-fold>//GEN-END:|0-initialize|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
  /**
   * Performs an action assigned to the Mobile Device - MIDlet Started point.
   */
  public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
      switchDisplayable(null, getTxtContents());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
  }//GEN-BEGIN:|3-startMIDlet|2|
  //</editor-fold>//GEN-END:|3-startMIDlet|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
  /**
   * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
   */
  public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
  }//GEN-BEGIN:|4-resumeMIDlet|2|
  //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
  /**
   * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
   * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
   * @param nextDisplayable the Displayable to be set
   */
  public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
      Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
      if (alert == null) {
          display.setCurrent(nextDisplayable);
      } else {
          display.setCurrent(alert, nextDisplayable);
      }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
  }//GEN-BEGIN:|5-switchDisplayable|2|
  //</editor-fold>//GEN-END:|5-switchDisplayable|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
  /**
   * Called by a system to indicated that a command has been invoked on a particular displayable.
   * @param command the Command that was invoked
   * @param displayable the Displayable where the command was invoked
   */
  public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
      if (displayable == txtContents) {//GEN-BEGIN:|7-commandAction|1|41-preAction
          if (command == okCommand) {//GEN-END:|7-commandAction|1|41-preAction
              // write pre-action user code here
              switchDisplayable(null, getTxtRisultato());//GEN-LINE:|7-commandAction|2|41-postAction
              // write post-action user code here
          }//GEN-BEGIN:|7-commandAction|3|33-preAction
      } else if (displayable == txtRisultato) {
          if (command == exitCommand1) {//GEN-END:|7-commandAction|3|33-preAction
                // write pre-action user code here
              exitMIDlet();//GEN-LINE:|7-commandAction|4|33-postAction
                // write post-action user code here
          } else if (command == okCommand1) {//GEN-LINE:|7-commandAction|5|31-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|6|31-postAction
                // write post-action user code here
          }//GEN-BEGIN:|7-commandAction|7|7-postCommandAction
      }//GEN-END:|7-commandAction|7|7-postCommandAction
        // write post-action user code here
  }//GEN-BEGIN:|7-commandAction|8|
  //</editor-fold>//GEN-END:|7-commandAction|8|

  //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
  /**
   * Returns an initiliazed instance of exitCommand component.
   * @return the initialized component instance
   */
  public Command getExitCommand() {
      if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
          exitCommand = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
      }//GEN-BEGIN:|18-getter|2|
      return exitCommand;
  }
  //</editor-fold>//GEN-END:|18-getter|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand ">//GEN-BEGIN:|22-getter|0|22-preInit
  /**
   * Returns an initiliazed instance of okCommand component.
   * @return the initialized component instance
   */
  public Command getOkCommand() {
      if (okCommand == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
          okCommand = new Command("Ok", Command.OK, 0);//GEN-LINE:|22-getter|1|22-postInit
            // write post-init user code here
      }//GEN-BEGIN:|22-getter|2|
      return okCommand;
  }
  //</editor-fold>//GEN-END:|22-getter|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Getter: txtRisultato ">//GEN-BEGIN:|25-getter|0|25-preInit
  /**
   * Returns an initiliazed instance of txtRisultato component.
   * @return the initialized component instance
   */
  public Form getTxtRisultato() {
      if (txtRisultato == null) {//GEN-END:|25-getter|0|25-preInit
            // write pre-init user code here
          txtRisultato = new Form("Stato del traffico", new Item[] { getImageItem() });//GEN-BEGIN:|25-getter|1|25-postInit
          txtRisultato.addCommand(getOkCommand1());
          txtRisultato.addCommand(getExitCommand1());
          txtRisultato.setCommandListener(this);//GEN-END:|25-getter|1|25-postInit
            // write post-init user code here
      }//GEN-BEGIN:|25-getter|2|
      return txtRisultato;
  }
  //</editor-fold>//GEN-END:|25-getter|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand1 ">//GEN-BEGIN:|30-getter|0|30-preInit
  /**
   * Returns an initiliazed instance of okCommand1 component.
   * @return the initialized component instance
   */
  public Command getOkCommand1() {
      if (okCommand1 == null) {//GEN-END:|30-getter|0|30-preInit
            // write pre-init user code here
          okCommand1 = new Command("Ok", Command.OK, 0);//GEN-LINE:|30-getter|1|30-postInit
            // write post-init user code here
      }//GEN-BEGIN:|30-getter|2|
      return okCommand1;
  }
  //</editor-fold>//GEN-END:|30-getter|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand1 ">//GEN-BEGIN:|32-getter|0|32-preInit
  /**
   * Returns an initiliazed instance of exitCommand1 component.
   * @return the initialized component instance
   */
  public Command getExitCommand1() {
      if (exitCommand1 == null) {//GEN-END:|32-getter|0|32-preInit
            // write pre-init user code here
          exitCommand1 = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|32-getter|1|32-postInit
            // write post-init user code here
      }//GEN-BEGIN:|32-getter|2|
      return exitCommand1;
  }
  //</editor-fold>//GEN-END:|32-getter|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageItem ">//GEN-BEGIN:|26-getter|0|26-preInit
  /**
   * Returns an initiliazed instance of imageItem component.
   * @return the initialized component instance
   */
  public ImageItem getImageItem() {
      if (imageItem == null) {//GEN-END:|26-getter|0|26-preInit
            // write pre-init user code here
          imageItem = new ImageItem("Grande Raccordo Anulare", getImage1(), ImageItem.LAYOUT_DEFAULT, "<Missing Image>");//GEN-LINE:|26-getter|1|26-postInit
            // write post-init user code here
      }//GEN-BEGIN:|26-getter|2|
      return imageItem;
  }
  //</editor-fold>//GEN-END:|26-getter|2|

  //<editor-fold defaultstate="collapsed" desc=" Generated Getter: image1 ">//GEN-BEGIN:|29-getter|0|29-preInit
  /**
   * Returns an initiliazed instance of image1 component.
   * @return the initialized component instance
   */
  public Image getImage1() {
      if (image1 == null) {//GEN-END:|29-getter|0|29-preInit
            // write pre-init user code here
          try {//GEN-BEGIN:|29-getter|1|29-@java.io.IOException
              image1 = Image.createImage("/gra-num.png");
          } catch (java.io.IOException e) {//GEN-END:|29-getter|1|29-@java.io.IOException
                e.printStackTrace();
          }//GEN-LINE:|29-getter|2|29-postInit
            // write post-init user code here
      }//GEN-BEGIN:|29-getter|3|
      return image1;
  }
  //</editor-fold>//GEN-END:|29-getter|3|





  //<editor-fold defaultstate="collapsed" desc=" Generated Getter: txtContents ">//GEN-BEGIN:|39-getter|0|39-preInit
  /**
   * Returns an initiliazed instance of txtContents component.
   * @return the initialized component instance
   */
  public TextBox getTxtContents() {
      if (txtContents == null) {//GEN-END:|39-getter|0|39-preInit
            // write pre-init user code here
          txtContents = new TextBox("Dati ricevuti", null, 10000, TextField.ANY);//GEN-BEGIN:|39-getter|1|39-postInit
          txtContents.addCommand(getOkCommand());
          txtContents.setCommandListener(this);//GEN-END:|39-getter|1|39-postInit
            // write post-init user code here
      }//GEN-BEGIN:|39-getter|2|
      return txtContents;
  }
  //</editor-fold>//GEN-END:|39-getter|2|

boolean getViaStreamConnection(String url) throws IOException {
        boolean result = false;
        StreamConnection c = null;
        InputStream s = null;
        StringBuffer b = new StringBuffer();
        TextBox t = null;
        int size = 0;
        switchDisplayable(null, getTxtContents());
        txtContents.setString("Inizio...");
        try {
          txtContents.setString(txtContents.getString()+"Apro c...  \n");  
          c = (StreamConnection)Connector.open(url);
          txtContents.setString(txtContents.getString()+"Ok, apro s...  \n");  
          s = c.openDataInputStream();
          txtContents.setString(txtContents.getString()+"Ok, scarico... \n");  
          int ch;
          while((ch = s.read()) != -1) {
             b.append((char) ch);
             size++;
          }
          result = true;
          txtContents.setString(txtContents.getString()+"Ok, ciclo lettura finito.  \n");  
       } catch (Exception e) {
              txtContents.setString(txtContents.getString()+"Errore durante scaricamento: "+ e.getMessage()+  e.toString() + "\n");
              result = false;
        } finally {
           if(s != null) {
               txtContents.setString(txtContents.getString()+"Chiudo S.     \n");
             s.close();
           }
           if(c != null) {
               txtContents.setString(txtContents.getString()+"Chiudo C.     \n");
              c.close();
           }
           txtContents.setString(txtContents.getString()+"Fine finally. \n");
       }
        System.out.println(size);
       // txtContents.setMaxSize(size);
        String temp = b.toString();
        txtContents.setString(txtContents.getString()+"Da scaricare: " + Integer.toString(size) + ", scaricati "+ Integer.toString(temp.length()) + " byte.\n");
        contents = temp;
        if (b.length()==0) 
            result = false;
        return result;
    }

//public void readFile(){
//        try {
//            InputStream is = null;
//            int MAXLEN = 5000;
//            byte[] data = new byte[MAXLEN];
//            //String contenuto;
//
//            is = getClass().getResourceAsStream("traffic.txt");
//            if (is != null) {
//                is.read(data, 0, MAXLEN);  // Legge tutto il file.  
//                contents = new String(data, 0, MAXLEN);
//                System.out.println(contents);
//            }
//        } catch (java.io.IOException ex) {
//            System.out.println("Eccezione: errore generico nella lettura.");
//            ex.printStackTrace();
//        }
//         System.out.println("letto.");
//}

    public boolean getColors() {
        boolean result = false;
        try {
          for (int i = 0; i<=23; i++) {
              int line_start = contents.indexOf("<tr><td>"+name[i]);
              String temp = contents.substring(line_start,contents.length()-1);
              int color_pos = temp.indexOf("rgb")+4+line_start;
              String chunk = contents.substring(color_pos,color_pos+25);
              int R = Integer.parseInt(chunk.substring(0,chunk.indexOf(",")));
              System.out.print("R:" + Integer.toString(R));
              chunk = chunk.substring(chunk.indexOf(",")+1,chunk.indexOf(",")+15);
              int G = Integer.parseInt(chunk.substring(1,chunk.indexOf(",")));
              System.out.print(", G:" + Integer.toString(G));
              chunk = chunk.substring(chunk.indexOf(",")+1,chunk.length()); 
              int B = Integer.parseInt(chunk.substring(1,chunk.indexOf(")")));
              System.out.println(", B:" + Integer.toString(B));
              segment_color[i][KINT] = ColorCode(R,G,B);

              temp = contents.substring(color_pos+1,contents.length()-1);
              color_pos = temp.indexOf("rgb")+color_pos+5;
              chunk = contents.substring(color_pos,color_pos+25); // Memorizza terna RGB.
              int R1 = Integer.parseInt(chunk.substring(0,chunk.indexOf(","))); // Memorizza primo numero (R)
              chunk = chunk.substring(chunk.indexOf(",")+1,chunk.indexOf(",")+15); // Taglia via numero appena letto.
              int G1 = Integer.parseInt(chunk.substring(1,chunk.indexOf(","))); // Memorizza secondo numero (G)
              chunk = chunk.substring(chunk.indexOf(",")+1,chunk.length()); // Taglia via numero appena letto.
              int B1 = Integer.parseInt(chunk.substring(1,chunk.indexOf(")"))); // Memorizza terzo numero (B) 
              segment_color[i][KEXT] = ColorCode(R1,G1,B1); //[R1,G1,B1]

              System.out.print(Integer.toString(R)+","+Integer.toString(G)+","+Integer.toString(B) + " diventa: ");
              System.out.println(Integer.toString( segment_color[i][KINT][0])+","+Integer.toString( segment_color[i][KINT][1])+","+Integer.toString( segment_color[i][KINT][2]));
        }
        result = true;
      } catch (Exception e) {
             System.out.println("Errore durante estrazione colori da file.\n");
             txtContents.setString(txtContents.getString()+"Errore durante estrazione colori da file:" + e.toString()+ " \n");
             result = false;
      }
      return result;
}
      
    public int[] ColorCode(int R,int G,int B) {
    // Converte in valore personalizzato il colore rilevato per il segmento.
      int found = -1;
      int[] def =  {200,200,200};
      for (int i=0; i< CODES_NUMBER; i++) {
        if (( R == codes[i][0][0] ) && (G == codes[i][0][1]) && (B == codes[i][0][2])) {
          found = i;
          return codes[i][1]; 
        } else { // Unrecognized color code: return it.
            def[0] = R;
            def[1] = G;
            def[2] = B;
            return def;
        }
      }
      if (found == -1) {
        //
      } else {
        System.out.println("NON RICONOSCIUTO:"+Integer.toString(R)+","+Integer.toString(G)+","+Integer.toString(B));
    }
      return def;
}

class MyCanvas extends Canvas implements CommandListener {
  private Command exit;

  private mTrafficLC mTrafficLC;

  private Image imm_image; // Immutable image (to be loaded from filesystem)
  private Image mut_image; // Mutable image (i.e. drawable).

  public MyCanvas(mTrafficLC mTrafficLC) {
    this.mTrafficLC = mTrafficLC;
    exit = new Command("Exit", Command.EXIT, 1);
    addCommand(exit);
    setCommandListener(this);
    try {
        imm_image = Image.createImage("/gra-num.png"); // Load image from disk
    }
    catch (Exception e) {
        System.out.println("ERROR: Image gra-num.png not found.");
        txtContents.setString(txtContents.getString()+"ERROR: Image gra-num.png not found. \n");
        e.printStackTrace();
    }
    // Create mutable image same size of just loaded (and immutable) image:
    try {
        mut_image = Image.createImage(imm_image.getWidth(),imm_image.getHeight());
    }catch (Exception e) {
        System.out.println("ERRORE: impossibile copiare imm_image in mut_image.");
        txtContents.setString(txtContents.getString()+"ERRORE: impossibile copiare imm_image in mut_image: "+ e.toString()+ " \n");
        e.printStackTrace();
    }
  }

  protected void paint(Graphics g) {
      try {
        Graphics offGrap = mut_image.getGraphics(); // Get a working copy (=graphics) of the mutable image for drawing on it.
        offGrap.setColor(0xff0000);
        offGrap.drawImage(imm_image, 0, 0, 0); // Copy immutable (loaded) image into mutable image.
        for (int i=0; i<=22; i++) {
            offGrap.setColor(mTrafficLC.segment_color[i][KINT][0],mTrafficLC.segment_color[i][KINT][1],mTrafficLC.segment_color[i][KINT][2]);
            drawLineExt(offGrap,mTrafficLC.Segments[i][mTrafficLC.KINT][0],mTrafficLC.Segments[i][mTrafficLC.KINT][1],mTrafficLC.Segments[i+1][mTrafficLC.KINT][0],mTrafficLC.Segments[i+1][mTrafficLC.KINT][1],5);
            offGrap.setColor(mTrafficLC.segment_color[i][KEXT][0],mTrafficLC.segment_color[i][KEXT][1],mTrafficLC.segment_color[i][KEXT][2]);
            drawLineExt(offGrap,mTrafficLC.Segments[i][mTrafficLC.KEXT][0],mTrafficLC.Segments[i][mTrafficLC.KEXT][1],mTrafficLC.Segments[i+1][mTrafficLC.KEXT][0],mTrafficLC.Segments[i+1][mTrafficLC.KEXT][1],5);
        }
       offGrap.setColor(mTrafficLC.segment_color[23][KINT][0],mTrafficLC.segment_color[23][KINT][1],mTrafficLC.segment_color[23][KINT][2]);
       drawLineExt(offGrap,mTrafficLC.Segments[23][mTrafficLC.KINT][0],mTrafficLC.Segments[23][mTrafficLC.KINT][1],mTrafficLC.Segments[0][mTrafficLC.KINT][0],mTrafficLC.Segments[0][mTrafficLC.KINT][1],5);
       offGrap.setColor(mTrafficLC.segment_color[23][KEXT][0],mTrafficLC.segment_color[23][KEXT][1],mTrafficLC.segment_color[23][KEXT][2]);
       drawLineExt(offGrap,mTrafficLC.Segments[23][mTrafficLC.KEXT][0],mTrafficLC.Segments[23][mTrafficLC.KEXT][1],mTrafficLC.Segments[0][mTrafficLC.KEXT][0],mTrafficLC.Segments[0][mTrafficLC.KEXT][1],5);
       g.drawImage(mut_image, 0,0, Graphics.LEFT | Graphics.TOP);  
      } catch (Exception e) {
        System.out.println("ERRORE in routine PAINT");
        txtContents.setString(txtContents.getString()+"ERRORE in routine PAINT: "+ e.toString() + "  \n");
        e.printStackTrace();          
      }
  }
  
//  protected void drawLineExtold(Graphics g, int xstart, int ystart, int xend, int yend, int width) {
//      int sign;
//      int ratio,alfa;
//      int new_yend, new_xend;
//      if (xend != xstart) {
//          ratio=FP.Div((yend-ystart),(xend-xstart));  
//          alfa=FP.ArcTan(ratio);
//      } else {
//          alfa = FP.PI/2;
//      }
//      
//      
//      if (xend-xstart<0) {
//        sign = -1;
//      } else {
//        sign = 1;
//      }
//      new_xend = xend + sign*width*FP.toInt(FP.Sin(alfa));
//      new_yend = yend+sign*width*FP.toInt(FP.Cos(alfa));
//      g.drawLine(xstart,ystart,new_xend,new_yend);
// 
//       System.out.print(xstart);
//      System.out.print(" ");
//      System.out.print(ystart);
//      System.out.print(" ");
//      System.out.print(xend);
//      System.out.print(" ");
//      System.out.print(yend);
//      System.out.print(" ");
//      System.out.print(new_xend);
//      System.out.print(" ");
//      System.out.println(new_yend);
//     
//      
//      /*   alfa =  (math.atan((segments[i][KINT][1]-cr[1])/(segments[i][KINT][0]-cr[0])))
//      segments[i][KEXT][1] = segments[i][KINT][1] + sign*(LINE_WIDTH*2*math.sin(alfa))
//      segments[i][KEXT][0] = segments[i][KINT][0] +sign*(LINE_WIDTH*2*math.cos(alfa))*/
//
//  }

  
//   protected void drawLineExtRetta(Graphics g, int x1, int y1, int x2, int y2, int width) {
//       // Y = m*x+q
//       int y;
//       if (x2-x1 != 0) {
//           int mf = FP.Div((y2-y1),(x2-x1));
//           int qf = FP.Div((y1*(x2-x1)+x1*(y2-y1)),(x2-x1));
//           int q = FP.toInt(qf);
//           System.out.print("mf,qf=");
//           System.out.print(FP.toInt(mf));
//           System.out.print(",");
//           System.out.println(FP.toInt(qf));
//           for (int x=x1; x<=x2; x++){
//               int xf = FP.intToFP(x);
//               int mxf = FP.Mul(mf,xf);
//               int mx = FP.toInt(mxf);
//               y = (int)(mx+q);   // Autocasting
//               System.out.print(x);
//               System.out.print(",");
//               System.out.println(y);
//               g.drawLine(x1,y1,x,y);  
//           }
//        } else {
//           System.out.println("Caso particolare...");
//        }
//   }
   
   protected void drawLineExt(Graphics g, int x1, int y1, int x2, int y2, int width) {
       for (int add=1; add<=width; add++) {
            g.drawLine(x1+add,y1,x2+add,y2);           
            g.drawLine(x1,y1+add,x2,y2+add);           
       }
   }
   
  public void commandAction(Command command, Displayable display) {
    if (command == exit) {
      mTrafficLC.exitMIDlet();
    }
  }
}
}
